package com.yupi.springbootinit.datasource;

import com.yupi.springbootinit.model.enums.SearchTypeEnum;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 注册器模式，先注册好多个数据源
 * @author gan
 * @date 2023/4/21 13:10
 */
@Component
@Data
public class DataSourceRegistry {
    @Resource
    private PictureDataSource pictureDataSource;

    @Resource
    private UserDataSource userDataSource;

    @Resource
    private PostDataSource postDataSource;

    @Resource
    private VideoDataSource videoDataSource;

    private Map<String, DataSource> dataSourceMap;

    //这里也能用静态代码块去初始化
    @PostConstruct
    public void doInit(){
        dataSourceMap = new HashMap<>();
        dataSourceMap.put(SearchTypeEnum.POST.getValue(), postDataSource);
        dataSourceMap.put(SearchTypeEnum.USER.getValue(), userDataSource);
        dataSourceMap.put(SearchTypeEnum.PICTURE.getValue(), pictureDataSource);
        dataSourceMap.put(SearchTypeEnum.VIDEO.getValue(), videoDataSource);
    }

    public DataSource getDataSourceByType(String type){
        return dataSourceMap == null ? null : dataSourceMap.get(type);
    }
}
